<?php

require_once $_SERVER["DOCUMENT_ROOT"] . "/private/functions.php";
require_once $_SERVER["DOCUMENT_ROOT"] . "/private/config.php";

class World
{
	private function __construct() {}
	private function __destruct() {}
	private function __clone() {} 
	
	public static function init()
	{
		require_once $_SERVER["DOCUMENT_ROOT"] . "/private/world_data.php";
		
		if (isset($worldData)) 
		{
			$time = time();
			$from = $worldData["lastInit"];
			
			$count = 0;
			while ($time - $from > 0)
			{
				if ($time - $from > GO_TIME_STEP)
					$to = $from + GO_TIME_STEP;
				else 
					$to = $time;
				World::round($from, $to);
				$from = $to;
				
				++$count;
			}
			
		}
		
		$worldData = array
		(
			"lastInit" => time(),	
		);
		
		$format = "<?php\n\t\$worldData = %s;\n?>";
		
		file_put_contents($_SERVER["DOCUMENT_ROOT"] . "/private/world_data.php", 
			sprintf($format, var_export($worldData, true)), LOCK_EX);
	}
	
	private static function round($from, $to)
	{
		$dt = $to - $from;
		$percent = floatval($dt) / 3600.0;
		
		$playerList = PlayerRegistry::i()->playerList();
		
		foreach ($playerList as $player)
		{
			if ($player->registerDate() > $from)
				continue;
			
			$player->setGold($player->gold() + floatval(300.0 * $percent));
		}
	}
}

?>